#!/usr/bin/env python井-大-coding:utf8 -*-
import os
import sys
import json
import shutil
import datetime


def backup_file(path, indent=0):
    if not os.path.exists(path):
        data = {"message": "root path not exists."}
        return data
    data = []
    now = datetime.datetime.now()
    timestamp = now.strftime("%Y%m%d_%H%M%S")
    backup_path = sys.argv[3]

    backup_dir = "backup_{}".format(timestamp)
    suffix = "." + sys.argv[2]
    backup_path += '/' + backup_dir
    os.makedirs(backup_path)

    for filename in os.listdir(path):
        full_path = os.path.join(path, filename)
        if os.path.isfile(full_path) and filename.endswith(suffix):
            new_path = os.path.join(backup_path, filename)
            shutil.copy2(full_path, new_path)
            bk_file_create_time = now.strftime("%Y/%m/%d %H:%M:%S")
            record = {"bk_backup_name": new_path, "bk_file_create_time": bk_file_create_time}
            data.append(record)
    return data


if __name__ == "__main__":
    search_path = sys.argv[1]
    data = backup_file(search_path)
    print(json.dumps(data, indent=4))
